<template>

    <div class="addMerchantBox" v-loading="loading">
        <el-button class="el-icon-arrow-left" size="mini" type="primary" style="margin-bottom:10px;"
                   @click="handBackList">返回
        </el-button>
        <el-form ref="form" :model="initial_data" :rules="rules">
            <el-form-item label="管理员昵称" prop="nickname">
                <el-input v-model="initial_data.nickname" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="管理员账号" prop="username">
                <el-input v-model="initial_data.username" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="管理员密码" prop="password">
                <el-input v-model="initial_data.password" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item
                    label="管理员头像"
                    class="picUpload"
                    style="display:flex;flex-direction:row"
                    prop="avatar"
            >
                <div class="picUpload" style="display:flex;flex-direction:row">
                    <div>
                        <div>
                            <el-upload
                                    :http-request="handlePictureCardPreview"
                                    :multiple="false"
                                    action
                                    list-type="picture-card"
                                    name="avatar"
                                    ref="businessLicenseUpload"
                            >
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog
                                    :modal="false"
                                    :center="true"
                                    :show-close="false"
                                    class="commonVisible"
                                    :visible.sync="avatarVisible"
                                    :fullscreen="true"
                            >
                                <img alt class :src="initial_data.avatar" v-show="avatarVisible">
                            </el-dialog>
                        </div>
                    </div>
                </div>
            </el-form-item>

            <el-form-item label="角色" prop="role">
                <el-select
                        multiple="multiple"
                        v-model="initial_data.role"
                        placeholder="请选择角色（可多选）"
                        style="width:300px"
                        @change="rolesFn($event)"
                >
                    <el-option v-for="(item) in rolesList" :key="item.id" :label="item.name"
                               :value="item.id"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="权限" prop="permissions">
                <el-select multiple="multiple" v-model="initial_data.permissions" placeholder="请选择权限（可多选）">
                    <el-option
                            v-for="(item) in permissionsList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="initial_data.status">
                    <el-radio label="0" value="0">正常</el-radio>
                    <el-radio label="1" value="1">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>

        <div class="submitBtnBox">
            <el-button class="submitBtn" @click="submitFn" type="primary">确认添加</el-button>
        </div>
    </div>
</template>

<script>
    export default {
        name: "permission-addUser",
        components: {},
        data() {
            return {
                initial_data: {
                    //获取初始数据
                    token: localStorage.getItem("user_token"), //token
                    username: "",
                    password: "",
                    nickname: "",
                    avatar: "",
                    role: "",
                    permissions: [],
                    status: ""
                },
                avatarVisible: false,
                rolesList: [],
                permissionsList: [],
                loading: false,
                roleID: [],
                rules: {
                    username: [{required: true, message: "请输入昵称", trigger: "blur"}],
                    password: [{required: true, message: "请输入密码", trigger: "blur"}],
                    nickname: [{required: true, message: "请输入账号", trigger: "blur"}],
                    avatar: [{required: true, message: "请上传头像", trigger: "blur"}],
                    role: [{required: true, message: "请选择角色", trigger: "blur"}],
                    permissions: [
                        {required: true, message: "请选择权限", trigger: "blur"}
                    ],
                    status: [{required: true, message: "请选择状态", trigger: "blur"}]
                }
            };
        },
        watch: {},
        methods: {
            //获取下拉角色信息
            getRoles() {
                this.$http
                    .get("/web/user/roles/list", {
                        params: {
                            token: localStorage.getItem("user_token"),
                            pageSize: 999
                        }
                    })
                    .then(response => {
                        if (response.data.status == "success") {
                            this.rolesList = response.data.data.list;
                        }
                    })
                    .catch(error => {
                        console.log("error:", error);
                    });
            },
            //获取下拉权限节点
            getPermissions() {
                this.$http
                    .get("/web/user/permissions/no/page/list", {
                        params: {
                            token: localStorage.getItem("user_token"),
                            pageSize: 999
                        }
                    })
                    .then(response => {
                        if (response.data.status == "success") {
                            this.permissionsList = response.data.data;
                        }
                    })
                    .catch(error => {
                        console.log("error:", error);
                    });
            },
            //上传图片:folder是传给服务的文件名,用作图片分类
            handlePictureCardPreview(file) {
                this.loading = true;
                console.log("file-file:", file.filename);
                let imageFile = file.file;
                let formData = new FormData();
                formData.append("image", imageFile);
                formData.append("action", file.filename);
                this.$http
                    .post("/api/tool/ali/upload/image", formData)
                    .then(response => {
                        if (file.filename == "avatar") {
                            this.initial_data.avatar = response.data.data;
                        }
                        this.loading = false;
                    })
                    .catch(error => {
                        console.log("图片上传失败");
                    });
            },

            rolesFn(event) {
                this.initial_data.permissions = [];
                this.roleID = event;
                this.$http
                    .get("/web/user/roles/permissions", {
                        params: {
                            token: localStorage.getItem("user_token"),
                            id: this.roleID
                        }
                    })
                    .then(response => {
                        if (response.data.status == "success") {
                            for (let i = 0; i < response.data.data.length; i++) {
                                this.initial_data.permissions.push(response.data.data[i].id);
                            }
                        }
                    })
                    .catch(error => {
                        console.log("rolesFnerror:", error);
                    });
            },

            handBackList() {
                this.$router.push({name: "permissionUser"});
            },

            submitFn() {
                this.$refs.form.validate(valid => {
                    if (!valid) {
                        return false;
                    } else {
                        this.loading = true;
                        this.$nextTick(() => {
                            this.$http
                                .post("/web/user/add", this.initial_data)
                                .then(response => {
                                    if (response.data.status == "success") {
                                        this.$message({
                                            message: "添加成功",
                                            duration: 6000
                                        });

                                        this.$router.push({
                                            name: "permissionUser"
                                        });
                                    } else {
                                        this.$message({
                                            message: "添加失败，原因：" + response.data.failedMsg,
                                            duration: 6000
                                        });
                                    }
                                    this.loading = false;
                                })
                                .catch(error => {
                                    this.$message({
                                        message: "添加失败，原因：" + error,
                                        duration: 6000
                                    });
                                    this.loading = false;
                                });
                        });
                    }
                });
            }
        },
        mounted() {
            this.getPermissions();
            this.getRoles();
        }
    };
</script>

<style scoped lang="scss">
    @import "./user.scss";
</style>
